import { defineComponent, reactive, ref, computed, createVNode, onMounted } from "vue";
import LForm, { LFormItem } from "@/components/public/lForm/lForm";
import styles from "./insureBatchSonPage.module.less";
import Page from "@/components/public/page/page";
import { CardWithTitle } from "@/components/public/card/card";
import {
  $groupOrderImportPeopleData,
  $insuredValidate,
  $insuredDoImport,
  $groupOrderImportPeopleTask,
  $insuredInsuredFailedPeople,
} from "@/api/groupOrder/groupOrder";
import {
  DoubleRightOutlined,
  CheckOutlined,
  InboxOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { message, UploadProps } from "ant-design-vue";
import { Modal } from "ant-design-vue";
import useXlsx from "@/hooks/useXlsx";
import useNavigator from "@/hooks/useNavigator";
export default defineComponent({
  emits: ["cancel", "confirm"],
  setup(props, { emit, expose }) {
    const xlsx = useXlsx();
    const title = ref("" as any);
    const navigator = useNavigator();
    const state = reactive({
      nextIndex: 0,
      fileList: [],
      citylist: [],
      arealist: [],
      number: "",
      errorNumber: "",
      fileName: "",
      datalist: [],
      loading: false,
      isFail:false,
      columns: [
        {
          title: "保司保单号",
          dataIndex: "insurance_order_no",
          key: "insurance_order_no",
          align: "center",
        },
        // {
        //   title: "续保/终保",
        //   dataIndex: ["is_new", "label"],
        //   key: "is_new",
        //   align: "center",
        // },
        {
          title: "被保人姓名",
          dataIndex: "name",
          key: "name",
          align: "center",
        },
        {
          title: "身份证号码",
          dataIndex: "id_no",
          key: "id_no",
          align: "center",
        },
        // {
        //   title: "生日",
        //   dataIndex: "birthday",
        //   key: "birthday",
        //   align: "center",
        // },
        // {
        //   title: "性别",
        //   dataIndex: ["sex", "label"],
        //   key: "sex",
        //   align: "center",
        // },
        // {
        //   title: "手机号",
        //   dataIndex: "mobile",
        //   key: "mobile",
        //   align: "center",
        // },
        // {
        //   title: "所在市",
        //   dataIndex: ["city_id", "label"],
        //   key: "city_id",
        //   align: "center",
        // },
        // {
        //   title: "所在区县",
        //   dataIndex: ["area_id", "label"],
        //   key: "area_id",
        //   align: "center",
        // },
        // {
        //   title: "所在乡镇/街道",
        //   dataIndex: ["street_id", "label"],
        //   key: "street_id",
        // },
        // {
        //   title: "所在村/社区",
        //   dataIndex: ["village_id", "label"],
        //   key: "village_id",
        //   align: "center",
        // },
        // {
        //   title: "商保/低保",
        //   dataIndex: ["people_type", "label"],
        //   align: "center",
        //   width: "180px",
        // },
        {
          title: "生效时间",
          dataIndex: "people_start_date",
          key: "people_start_date",
          align: "center",
        },
        {
          title: "承保时间",
          dataIndex: "insure_time",
          key: "insure_time",
          align: "center",
        },
        {
          title: '验证结果',
          dataIndex: "status",
          key: "status",
          align: "center",
        },
        {
          title: "备注",
          dataIndex: "remark",
          key: "remark",
          align: "center",
        },
      ],
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
      },
    } as any);
    const cancelHandler = () => {
      //提交投保人信息
      if (state.nextIndex == 0) {
         navigator.back();
      } else if (state.nextIndex == 1) {
        Modal.confirm({
          title: "提示",
          icon: createVNode(ExclamationCircleOutlined),
          content: "若返回上一步,需要重新上传文件,成功上传的内容将不会被保存",
          okText: "确认",
          cancelText: "取消",
          onOk: () => {
            state.fileList = [];
            state.fileName = "";
            state.nextIndex = 0;
          },
        });
      } else if (state.nextIndex == 2) {

        emit("confirm");
        navigator.back();
      }
    };
    var hide: any;
    const confirmHandler = () => {
      //提交投保人信息
      if (state.nextIndex == 0) {
        uploadFile();
      } else if (state.nextIndex == 1) {
        Modal.confirm({
          title: "提示",
          icon: createVNode(ExclamationCircleOutlined),
          content:(state.isFail)?"有失败数据请下载表格,重新上传":"是否确认信息已上传完毕",
          okText: "确认",
          cancelText: "取消",
          onOk: async () => {
            if(state.isFail)
              {
                title.value = "正在导出文件...";
                xlsx.init({
                  limit: 2000,
                  otherParams:{number: state.number,},
                  service: $insuredValidate
                })
                await xlsx.defineList([
                  {
                    label: '系统保单号',
                    value: 'order_no',
                    width: 25,
                  },
                  {
                    label: '保司保单号',
                    value: 'insurance_order_no',
                    width: 25,
                  },
                  {
                    label: '被保人姓名',
                    value: 'name',
                    width: 25,
                  },
                  {
                    label: '证件号码',
                    value: 'id_no',
                    width: 25,
                  },
                  {
                    label: '本次生效日期',
                    value: 'people_start_date',
                    width: 25,
                  },
                  {
                    label: '承保时间',
                    value: 'insure_time',
                    width: 25,
                  },
                  {
                    label: '验证结果',
                    value: ["status","label"],
                    width: 25,
                  },
                  {
                    label: '备注',
                    value: 'remark',
                    width: 50,
                  },
                  
                ]);
                await xlsx.exportToExcel('团单承保.xlsx');
              }
              else
              {
                state.loading = true;
            hide = message.loading('导入中', 0);
            searchInsure();
              }
          },
        });
      }
    };
    var hideOut: any;
    //多次查询处理结果
    const searchInsure = () => {
      $insuredDoImport({
        "number": state.number
      }).then((res: any) => {
        state.loading = false;
        setTimeout(hide);
        message.success("导入成功");
        state.nextIndex = 2;
        // if (res?.data?.status == 10) {
        //   searchInsure();
        // }
        // else if (res?.data?.status == -1) {
        //   state.loading = false;
        //   setTimeout(hide);
        //   message.error("导入失败,请联系技术人员");
        // }
        // else if (res?.data?.status == 1) {
        //   state.loading = false;
        //   setTimeout(hide);
        //   message.success("导入成功");
        //   state.nextIndex = 2;
        //   // if (res?.data?.download == true) {
        //   //   Modal.confirm({
        //   //     title: "提示",
        //   //     icon: createVNode(ExclamationCircleOutlined),
        //   //     content:
        //   //       "有部分信息未导入,是否下载重新导入",
        //   //     okText: "确认",
        //   //     cancelText: "取消",
        //   //     onOk: () => {
        //   //       $insuredInsuredInsuredFaliedTask({ number: state.number }).then((res: any) => {
        //   //         state.errorNumber = res?.data?.number;
        //   //         hideOut = message.loading('导出中', 0);
        //   //         $insuredInsuredFailedPeople({
        //   //           import_number: state.number,
        //   //           number: state.errorNumber,
        //   //         })
        //   //         searchError();
        //   //       })

        //   //     },
        //   //   });
        //   // }
        // }
      }).catch(()=>{
        state.loading = false;
        setTimeout(hide);
      })
    }
    const searchError = () => {
      $insuredInsuredFailedPeople({
        import_number: state.number,
        number: state.errorNumber,
      }).then((res: any) => {

        if (res?.data?.status === 1) {
          setTimeout(hideOut);
          window.open(res.data.url);
          state.fileList = [];
          state.fileName = "";
          state.nextIndex = 0;
        }
        else if (res?.data?.status === 10) {
          searchError();
        }
        else if (res?.data?.status == -1) {
          setTimeout(hideOut);
          message.error("导出失败,请联系技术人员");
        }
      })
    }
    //上传文件
    const uploadFile = () => {
      state.isFail = false;
      const formData: FormData = new FormData();
      formData.set("file", state.fileList[0].originFileObj);
      $groupOrderImportPeopleData(
        { number: state.number },
        { file: state.fileList[0].originFileObj }
      ).then((res: any) => {
        state.nextIndex = 1;
        $insuredValidate({
          page: 1,
          limit: 10,
          number: state.number,
        }).then((res: any) => {
          state.pagination.total = res.data?.total;
          state.pagination.current = res.data?.current_page;
          state.pagination.pageSize = res.data?.per_page;
          state.datalist = res.data?.data || [];
          if(res.data?.data[0].status.label === "失败")
          {
             state.isFail = true;
          }
        });
      });
    };
    //手动上传
    const beforeUpload: UploadProps["beforeUpload"] = (file) => {
      state.fileName = file.name;
      state.fileList = [file];
      return false;
    };
    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      state.pagination.current = pag.current;
      state.pagination.pageSize = pag.pageSize;
      $insuredValidate({
        page: state.pagination.current,
        limit: state.pagination.pageSize,
        number: state.number,
      }).then((res: any) => {
        state.pagination.total = res.data?.total;
        state.datalist = res.data?.data || [];
      });
    };
    // 选中项变更
    const onSelectChange = (changableRowKeys: any[]) => {
      state.selectedRowKeys = changableRowKeys;
    };
    const rowSelection = computed(() => {
      return {
        selectedRowKeys: state.selectedRowKeys,
        fixed: true,
        onChange: onSelectChange,
      };
    });
    const addPopupRef = ref(null as any);
    const open = (e: any) => {
      state.nextIndex = 0;
      state.fileList = [];
      state.citylist = [];
      state.arealist = [];
      state.number = "";
      state.fileName = "";
      state.datalist = [];
      //获取城市
      $groupOrderImportPeopleTask({}).then((res: any) => {
        state.number = res?.data?.number;
      });
      addPopupRef.value.open();
    };
    const close = () => {
      addPopupRef.value.close();
    };
    expose({
      open,
      close,
    });
    onMounted(()=>{
        state.nextIndex = 0;
        state.fileList = [];
        state.citylist = [];
        state.arealist = [];
        state.number = "";
        state.fileName = "";
        state.datalist = [];
        //获取城市
        $groupOrderImportPeopleTask({}).then((res: any) => {
          state.number = res?.data?.number;
        });
    })
    //上传清单
    const UploadChecklist = () => (
      <div class={styles.uploadChecklist_box}>
        <div class={styles.head_box}>
          <div class={styles.head_left_box}>
            {state.nextIndex > 0 ? (
              <div class={styles.number_select_box}>
                <CheckOutlined />
              </div>
            ) : (
              <div
                class={[
                  styles.numberOne_box,
                ]}
              >
                1
              </div>
            )}
            <div class={styles.content_box}>
              <div class={styles.label_box}>导入承保文件</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
          <div class={styles.icon_box}>
            <DoubleRightOutlined />
          </div>
          <div class={styles.head_left_box}>
            {state.nextIndex > 1 ? (
              <div class={styles.number_select_box}>
                <CheckOutlined />
              </div>
            ) : (
              <div
                class={[
                  styles.numberOne_box,
                  state.nextIndex < 1 && styles.numberOne_current_box,
                ]}
              >
                2
              </div>
            )}
            <div class={styles.content_box}>
              <div class={styles.label_box}>确认上传结果</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
          <div class={styles.icon_box}>
            <DoubleRightOutlined />
          </div>
          <div class={styles.head_left_box}>
            <div
              class={[
                styles.numberOne_box,
                state.nextIndex < 2 && styles.numberOne_current_box,
              ]}
            >
              3
            </div>
            <div class={styles.content_box}>
              <div class={styles.label_box}>上传成功</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
        </div>
        <div class={styles.body_box}>
          {state.nextIndex == 0 && (
            <div class={styles.content_box}>
              {/* <div class={styles.content_head_box}>
                <a-button
                  type="primary"
                  size="small"
                  onClick={() => {
                    $getGroup({}).then((res: any) => {
                      window.open(res.data.url);
                    });
                  }}
                >
                  下载模版
                </a-button>
                <div class={styles.content_label_box}>点击下载团单模版</div>
              </div> */}
              <div class={styles.uploadBox}>
                <a-upload-dragger
                  v-model:fileList={state.fileList}
                  name="file"
                  before-upload={beforeUpload}
                  showUploadList={false}
                >
                  <p class="ant-upload-drag-icon">
                    <InboxOutlined></InboxOutlined>
                  </p>
                  {state.fileName ? (
                    <p class="ant-upload-text">{state.fileName}</p>
                  ) : (
                    <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
                  )}
                </a-upload-dragger>
              </div>
            </div>
          )}
          {state.nextIndex > 0 && (
            <div class={styles.group_box}>
              {state.nextIndex == 2 && (
                <div class={styles.group_order_box}>
                  <div class={styles.group_order_round_box}>
                    <CheckOutlined />
                  </div>
                  <div class={styles.group_order_label_box}>团单添加成功</div>
                </div>
              )}
              <Grouplist />
            </div>
          )}
        </div>
      </div>
    );
    //上传团单列表结果
    const Grouplist = () => (
      <div style={{ width: "100%" }}>
        <a-table
          dataSource={state.datalist}
          columns={state.columns}
          pagination={state.pagination}
          scroll={{ x: 2000 }}
          onChange={tableChangeHandler}
          v-slots={{
            bodyCell: ({ column, record }: any) => {
              if (column.dataIndex == "status") {
                column.title = (state.nextIndex == 1) ? "验证结果" : "处理结果"
                if (record.status.value == "1") {
                  return (
                    <div style={{ color: "green" }}>{record.status.label}</div>
                  );
                } else {
                  return (
                    <div style={{ color: "red" }}>{record.status.label}</div>
                  );
                }
              }
            },
          }}
        />
      </div>
    );
    const Components = () => (
        <Page>
        <CardWithTitle title="批量承保">
        <div class={styles.orderEntryAdd}>
          <UploadChecklist />
          <div class={styles.btn_Box}>
            <a-button
              size="small"
              style={{ width: "55px" }}
              onClick={() => cancelHandler()}
            >
              {state.nextIndex == 2
                ? "关闭"
                : state.nextIndex == 0
                  ? "取消"
                  : "上一步"}
            </a-button>
            {state.nextIndex != 2 && (
              <div class={styles.right_btn_box}>
                <a-button
                  type="primary"
                  size="small"
                  loading={state.loading}
                  onClick={() => confirmHandler()}
                >
                  下一步
                </a-button>
              </div>
            )}
          </div>
        </div>
        </CardWithTitle>
        </Page>
    );
    return {
      Components,
    };
  },
  render() {
    return <this.Components />;
  },
});